package io.gitee.zhangbinhub.admin.component

import io.gitee.zhangbinhub.acp.core.common.CommonTools
import io.gitee.zhangbinhub.admin.constant.WorkFlowConstant
import io.gitee.zhangbinhub.admin.entity.Organization
import io.gitee.zhangbinhub.admin.entity.Role
import io.gitee.zhangbinhub.admin.service.OrganizationService
import io.gitee.zhangbinhub.admin.service.RoleService
import io.gitee.zhangbinhub.admin.service.UserService
import io.gitee.zhangbinhub.admin.vo.UserVo
import org.dromara.warm.flow.ui.dto.HandlerFunDto
import org.dromara.warm.flow.ui.dto.HandlerQuery
import org.dromara.warm.flow.ui.dto.TreeFunDto
import org.dromara.warm.flow.ui.service.HandlerSelectService
import org.dromara.warm.flow.ui.vo.HandlerFeedBackVo
import org.dromara.warm.flow.ui.vo.HandlerSelectVo
import org.noear.solon.annotation.Component

@Component
class WorkFlowSelectService(
    private val roleService: RoleService,
    private val organizationService: OrganizationService,
    private val userService: UserService
) : HandlerSelectService {
    override fun getHandlerType(): MutableList<String> {
        return mutableListOf("用户", "角色", "部门")
    }

    override fun getHandlerSelect(query: HandlerQuery): HandlerSelectVo =
        when (query.handlerType) {
            "角色" -> getRole(query)
            "部门" -> getDept(query)
            "用户" -> getUser(query)
            else -> HandlerSelectVo()
        }

    private fun getRole(query: HandlerQuery): HandlerSelectVo =
        roleService.getRoleList().let { roleList ->
            if (!CommonTools.isNullStr(query.handlerCode)) {
                roleList.filter { role -> role.code.contains(query.handlerCode) }
            } else {
                roleList
            }
        }.let { roleList ->
            if (!CommonTools.isNullStr(query.handlerName)) {
                roleList.filter { role -> role.name.contains(query.handlerName) }
            } else {
                roleList
            }
        }.let { roleList ->
            val handlerFunDto = HandlerFunDto(roleList, roleList.size.toLong())
                .setStorageId { role -> "${WorkFlowConstant.PERMISSION_ROLE_PREFIX}${role.id}" }
                .setHandlerCode(Role::code) // 权限编码
                .setHandlerName(Role::name) // 权限名称
            getHandlerSelectVo(handlerFunDto)
        }

    private fun getDept(query: HandlerQuery): HandlerSelectVo =
        organizationService.getAllOrgList().let { organizationList ->
            if (!CommonTools.isNullStr(query.handlerCode)) {
                organizationList.filter { organization -> organization.code.contains(query.handlerCode) }
            } else {
                organizationList
            }
        }.let { organizationList ->
            if (!CommonTools.isNullStr(query.handlerName)) {
                organizationList.filter { organization -> organization.name.contains(query.handlerName) }
            } else {
                organizationList
            }
        }.let { organizationList ->
            val handlerFunDto = HandlerFunDto(organizationList, organizationList.size.toLong())
                .setStorageId { role -> "${WorkFlowConstant.PERMISSION_DEPT_PREFIX}${role.id}" }
                .setHandlerCode(Organization::code) // 权限编码
                .setHandlerName(Organization::name) // 权限名称
            getHandlerSelectVo(handlerFunDto)
        }

    private fun getUser(query: HandlerQuery): HandlerSelectVo {
        val userList = userService.getUserVoList().let { userVos ->
            if (!CommonTools.isNullStr(query.handlerCode)) {
                userVos.filter { userVo -> userVo.loginNo!!.contains(query.handlerCode) }
            } else {
                userVos
            }
        }.let { userVos ->
            if (!CommonTools.isNullStr(query.handlerName)) {
                userVos.filter { userVo -> userVo.name!!.contains(query.handlerName) }
            } else {
                userVos
            }
        }.let { userVos ->
            mutableListOf<UserVo>().apply {
                userVos.forEach { userVo ->
                    if (userVo.organizationSet.isEmpty()) {
                        this.add(userVo)
                    } else {
                        userVo.organizationSet.forEach { organizationVo ->
                            this.add(UserVo().also {
                                it.id = userVo.id
                                it.name = userVo.name
                                it.organizationMngSet = mutableSetOf(organizationVo)
                            })
                        }
                    }
                }
            }
        }
        val organizationList = organizationService.getAllOrgList()

        // 业务系统数据，转成组件内部能够显示的数据, total是业务数据总数，用于分页显示
        val handlerFunDto = HandlerFunDto(userList, userList.size.toLong())
            .setStorageId { user -> user.id }
            .setHandlerCode(UserVo::loginNo) // 权限编码
            .setHandlerName(UserVo::name) // 权限名称
            .setGroupName { user ->
                if (user.organizationSet.isNotEmpty()) {
                    user.organizationSet.first().name
                } else {
                    ""
                }
            }

        // 业务系统机构，转成组件内部左侧树列表能够显示的数据
        val treeFunDto: TreeFunDto<Organization> = TreeFunDto(organizationList)
            .setId { dept -> dept.id } // 左侧树ID
            .setName(Organization::name) // 左侧树名称
            .setParentId { dept -> dept.parentId } // 左侧树父级ID

        return getHandlerSelectVo(handlerFunDto, treeFunDto)
    }

    override fun handlerFeedback(storageIds: MutableList<String>?): MutableList<HandlerFeedBackVo> {
        val handlerFeedBackVos: MutableList<HandlerFeedBackVo> = mutableListOf()
        // 遍历storageIds，按照原本的顺序回显名称
        if (!storageIds.isNullOrEmpty()) {
            for (storageId in storageIds) {
                handlerFeedBackVos.add(
                    HandlerFeedBackVo().apply {
                        this.storageId = storageId
                        this.handlerName = when {
                            storageId.startsWith(WorkFlowConstant.PERMISSION_ROLE_PREFIX) -> {
                                try {
                                    roleService.getRoleInfo(storageId.substring(WorkFlowConstant.PERMISSION_ROLE_PREFIX.length)).name
                                } catch (e: Exception) {
                                    ""
                                }
                            }

                            storageId.startsWith(WorkFlowConstant.PERMISSION_DEPT_PREFIX) -> {
                                try {
                                    organizationService.getOrgInfo(storageId.substring(WorkFlowConstant.PERMISSION_DEPT_PREFIX.length)).name
                                } catch (e: Exception) {
                                    ""
                                }
                            }

                            else -> {
                                try {
                                    userService.getUserInfoById(storageId)?.name ?: ""
                                } catch (e: Exception) {
                                    ""
                                }
                            }
                        }
                    }
                )
            }
        }
        return handlerFeedBackVos
    }
}